package com.sjs.flow.http.advice;

import com.sjs.flow.http.exception.PlatformException;
import com.sjs.flow.http.response.AbstractResponse;
import com.sjs.flow.http.response.DefaultResponse;
import com.sjs.flow.protocol.PlatformErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.List;

/**
 * @author uto_dev_008
 * @desc GlobalExceptionHandler
 * @since 2021/11/22 16:55
 * Copyright (c) 2021 南京友拓信息技术有限公司 All rights reserved
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * Description： 拦截异常进行处理返回前台友好信息
     *
     * @param e 异常对象
     * @return java.lang.String 返回前台信息
     */
    @ExceptionHandler(Exception.class)
    public AbstractResponse exceptionHandler(Exception e) {
        //平台错误
        e.printStackTrace();
        if (e instanceof PlatformException) {
            if (e.getCause() != null) {
                logger.error("GlobalExceptionHandler unknown error:", e);
            }
            PlatformException platformException = (PlatformException) e;
            return DefaultResponse.error(platformException.getCode(), platformException.getMessage(), platformException.getData());
        }
        if (e.getCause() != null && e.getCause().getCause() instanceof PlatformException) {
            if (e.getCause().getCause() != null) {
                logger.error("GlobalExceptionHandler unknown error:", e);
            }
            PlatformException platformException = (PlatformException) e.getCause().getCause();
            return DefaultResponse.error(platformException.getCode(), platformException.getMessage(), platformException.getData());
        }
        //参数校验错误
        if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            return getValidExceptionFeildResult(bindException.getBindingResult().getFieldErrors());
        }
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException bindException = (MethodArgumentNotValidException) e;
            return getValidExceptionFeildResult(bindException.getBindingResult().getFieldErrors());
        }
        //post请求未传参数
        if (e instanceof HttpMessageNotReadableException) {
            return  DefaultResponse.error(PlatformErrorCode.HTTPMESSAGENOTREADABLE_ERROR.getCode());
        }

        //请求Content type不支持
        if (e instanceof HttpMediaTypeNotSupportedException) {
            return DefaultResponse.error(PlatformErrorCode.HTTPMEDIATYPENOTSUPPORTED_ERROR.getCode());
        }

        if (e instanceof HttpRequestMethodNotSupportedException) {
            return DefaultResponse.error(PlatformErrorCode.HTTPREQUESTMETHODNOTSUPPORTED_ERROR.getCode(),e.getMessage());
        }

        //文件超过大小
        if (e instanceof MaxUploadSizeExceededException) {
            return DefaultResponse.error(PlatformErrorCode.MAXUPLOADSIZE_ERROR.getCode());
        }

        //重复数据提交
        if (e instanceof DuplicateKeyException) {
            return DefaultResponse.error(PlatformErrorCode.DUPLICATEKEY_ERROR.getCode());
        }

        logger.error("GlobalExceptionHandler unknown error:", e);
        return DefaultResponse.error(10000103);
    }


    //参数校验异常处理
    private AbstractResponse getValidExceptionFeildResult(List<FieldError> fieldErrors) {
        StringBuilder sb = new StringBuilder();
        for (FieldError error : fieldErrors) {
            sb.append("[").append(error.getField()).append("]:");
            sb.append(error.getDefaultMessage()).append(";");
        }
        String message = sb.length() > 0 ? sb.substring(0, sb.length() - 1) : sb.toString();
        String errcode = Integer.toString(PlatformErrorCode.SYS_PARAM_NULL.getCode());
        return DefaultResponse.error(Integer.parseInt(errcode), message, false);
    }

}
